<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const rules: any = reactive({
  name: [required('咨询师名字不能为空！')],
  gradeId: [required('请选择咨询师等级！')],
  realmId: [required('请选择咨询师领域！')]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch(() => {
    // ElMessage.error()
  })

  if (valid) {
    const formData = await getFormData()
    // 处理上传图片地址
    if (formData.avatar.length > 1) {
      formData.avatar = formData.avatar[1].response.data.filePath
    } else {
      formData.avatar = formData.avatar[0].url.replace('http://127.0.0.1:9527/', '')
    }

    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
